package org.yufan.controller;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.yufan.bean.Item;
import org.yufan.bean.ItemDesc;
import org.yufan.common.JedisService;
import org.yufan.exception.CustomException;
import org.yufan.result.Result;
import org.yufan.result.ResultUtils;
import org.yufan.service.ItemService;
import org.yufan.service.impl.ItemServiceImpl;

import java.io.IOException;

/**
 * Created by zxd on 2018/3/28.
 */
@Controller
@RequestMapping("/item")
public class ItemController {

    private Logger LOGGER= LoggerFactory.getLogger(ItemController.class);

    @Autowired
    private ItemService itemService;

    @Autowired
    private JedisService jedisService;


    @RequestMapping(value = "/{itemId}",method = RequestMethod.GET)
    public String toItem(@PathVariable("itemId")Long itemId,Model model) throws IOException, CustomException {
        LOGGER.info("查询的商品id为{}",itemId);
        //查询商品基本信息
        Item item = itemService.queryItemById(itemId);
        LOGGER.info("------------------item:{}",item);
        //查询商品的详情信息
        ItemDesc itemDesc=itemService.queryItemDescById(itemId);
        model.addAttribute("item",item);
        //完善图片
        String image=item.getImage();
        LOGGER.info("image ----------------{}",image);
        if(StringUtils.isEmpty(image)){
            LOGGER.error("商品图片不存在,itemId:{}",itemId);
            throw new CustomException("商品图片不存在，请联系管理员!");
        }
        String[] images=image.split(",");
        model.addAttribute("images",images);
        model.addAttribute("itemDesc",itemDesc);
        return "item";
    }

    @RequestMapping(value = "/cache/delete/{itemId}",method = RequestMethod.GET)
    @ResponseBody
    public Result deleteCache(@PathVariable("itemId") Long itemId){
        //删除缓存 TODO 移到service中
        jedisService.hdel("item",itemId+"");
        LOGGER.info("删除了商品{}缓存",itemId);
        return ResultUtils.buildSuccess();
    }


}
